﻿using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Domain.Model;
using Infrastructure;
using System.Configuration;

namespace Web.Controllers
{
    /// <summary>
    /// 系统控制器
    /// </summary>
    public class SystemController : BasicController
    {
        /// <summary>
        /// 主页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <returns></returns>
        public ActionResult ValidCode()
        {
            var validCode = Infrastructure.ValidCode.NewValidCode();
            Session["ValidCode"] = validCode;
            using (var image = Infrastructure.ValidCode.ValidCodeToImage(validCode))
            {
                using (var ms = new MemoryStream())
                {
                    image.Save(ms, ImageFormat.Gif);
                    Response.Cache.SetNoStore();
                    Response.ClearContent();
                    Response.ContentType = "image/Gif";
                    return File(ms.ToArray(), "image/Gif");
                }
            }
        }

        /// <summary>
        /// 登录操作
        /// </summary>
        /// <param name="account">账号</param>
        /// <param name="password">密码</param>
        /// <param name="validCode">验证码</param>
        /// <returns></returns>
        [HttpPost]
        [Web.Filters.ActionLog("系统登录")]
        public ActionResult Login(string account, string password, string validCode)
        {
            account = account.NullThenEmpty().Trim();
            password = password.NullThenEmpty().Trim();
            validCode = validCode.NullThenEmpty().Trim();

            var vCode = Session["ValidCode"];
            if (vCode == null)
            {
                return Json(new { state = false, value = "会话已过期，请重新登录..." });
            }

            if (vCode.ToString() != validCode)
            {
                return Json(new { state = false, value = "验证码错误..." });
            }

            if (account.IsNullOrEmpty() || password.IsNullOrEmpty())
            {
                return Json(new { state = false, value = "账号或密码不能为空..." });
            }

            var user = this.DbContext.User.Where(u => u.Account == account).FirstOrDefault();

            if (user == null || user.Password != Infrastructure.Encryption.GetPasswordMd5(password))
            {
                return Json(new { state = false, value = "账号或密码不正确..." });
            }

            if (user.IsValid == false)
            {
                return Json(new { state = false, value = "账号已被冻结..." });
            }
            if (!user.Role.Name.Contains("管理员"))
            {
                return Json(new { state = false, value = "该账号不是管理员" });
            }

            Session["LoginUser"] = JsonSerializer.ToEntity<User>(JsonSerializer.ToJson(user));

            return Json(new { state = true, value = "/user" });
        }


        /// <summary>
        /// 登出
        /// </summary>
        /// <returns></returns>
        public ActionResult Logout()
        {
            Response.Cookies.Clear();
            Response.Expires = 0;
            Session.Abandon();
            Session.Clear();
            return RedirectToAction("index", "system");
        }

        /// <summary>
        /// 注册页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Registy()
        {
            var mdoel = new User();
            return View(mdoel);
        }

        /// <summary>
        /// 注册操作
        /// </summary>
        /// <param name="user">客户</param>
        /// <param name="validCode">验证码</param>
        /// <returns></returns>
        [HttpPost]
        [Web.Filters.ActionLog("账号注册")]
        public ActionResult Registy(User user, string validCode)
        {
            var vCode = Session["ValidCode"];
            if (vCode == null)
            {
                return Json(new { state = false, value = "会话已过期，请重新登录..." });
            }
            if (vCode.ToString() != validCode.NullThenEmpty().Trim())
            {
                return Json(new { state = false, value = "验证码错误..." });
            }

            if (ModelState.IsValid)
            {
                user.Password = Encryption.GetPasswordMd5(user.Password.Trim());
                user.RoleId = Global.Roles.CustomerID;
                this.DbContext.User.Add(user);
                this.DbContext.SaveChanges();
                Session["LoginUser"] = JsonSerializer.ToEntity<User>(JsonSerializer.ToJson(user));
                return Json(new { state = true, value = "/perfect/createstore" });
            }
            return Json(new { state = false, value = ModelState.FirstModelError().ErrorMessage });
        }

        /// <summary>
        /// 检查账号
        /// </summary>
        /// <param name="id">id</param>
        /// <param name="account">账号</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult CheckAccount(Guid id, string account)
        {
            var exists = this.DbContext.User.Any(item => item.ID != id && item.Account == account);
            return Json(new { state = !exists, message = "此账号已被注册" });
        }

        public ActionResult Log()
        {
            return View();
        }

        public ActionResult LogPage(int pageIndex, int pageSize)
        {
            var q = from l in this.DbContext.SystemLog where l.UserId == this.LoginUser.ID select l;
            var page = q.OrderByDescending(item => item.ActionTime).ToPage(pageIndex, pageSize);
            return this.PageResult(page.TotalCount, this.ViewHtml(page));
        }
    }
}
